package com.relife.sys.controller;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.relife.common.http.HttpUtil;
import com.relife.common.model.AjaxJson;
import com.relife.common.model.Client;
import com.relife.common.model.ClientManager;
import com.relife.common.model.Page;
import com.relife.common.utils.StringUtil;
import com.relife.core.easyui.Easyui;
import com.relife.core.entity.*;
import com.relife.core.qbc.QbcQuery;
import com.relife.sys.service.DepartService;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;


/**
 * 部门
 * 
 * @author WU
 * @date 2015-11-25 14:03:13
 */
@Controller
@RequestMapping("sys/department")
public class DepartmentController extends BaseController {
	@Autowired
	private DepartService departService;

	@RequestMapping("/departmentList")
	public String departmentList(HttpServletRequest req) {
		return "sys/department/departmentList";
	}

	/**
	 * 数据列表
	 * 
	 * @author WU
	 * @date 2015-11-25 14:03:13
	 * @param department
	 * @param page
	 */
	@RequestMapping("/listData")
	public void listData(DepartmentEntity department, Page page, HttpServletResponse res) {
		String id = department.getId();
		department.setId(null);
		QbcQuery qbc = new QbcQuery(department);
		if (StringUtil.isEmpty(id)) {
			qbc.add(Restrictions.isNull("parent.id"));
		} else {
			qbc.add(Restrictions.eq("parent.id", id));
		}
		this.departPermission(qbc);
		departService.getPage(qbc, page);
		Easyui.treegrid(page, res);

	}

	/**
	 * @author WU
	 * @date 2015-11-25 14:03:13
	 * @param department
	 * @param req
	 * @return
	 */
	@RequestMapping("/department")
	public String department(DepartmentEntity department, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(department.getId())) {
			department = departService.get(DepartmentEntity.class, department.getId());
		}
		req.setAttribute("page", department);
		return "sys/department/department";
	}

	/**
	 * 保存
	 * 
	 * @author WU
	 * @date 2015-11-25 14:03:13
	 * @param department
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/save")
	public AjaxJson save(DepartmentEntity department) {
		AjaxJson j = new AjaxJson();
		try {
			departService.saveDepart(department);
		} catch (Exception e) {
			e.printStackTrace();
			j.setException(e);
		}
		return j;
	}

	/**
	 * 删除
	 * 
	 * @author WU
	 * @date 2015-11-25 14:03:13
	 * @param department
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/del")
	public AjaxJson del(DepartmentEntity department) {
		AjaxJson j = new AjaxJson();
		try {
			departService.delete(department);
		} catch (Exception e) {
			e.printStackTrace();
			j.setException(e);
		}
		return j;
	}

	/**
	 * 上级部门
	 * 
	 * @author WU
	 * @date 2015-11-25 14:29:14
	 * @return
	 */
	@RequestMapping("/tree")
	public void tree(HttpServletResponse res) {
		QbcQuery qbc = new QbcQuery(DepartmentEntity.class);
		qbc.add(Restrictions.isNull("parent"));
		qbc.addOrder(Order.asc("orderBy"));
		this.openPermission(qbc);
		List<DepartmentEntity> list = departService.getList(qbc);
		Easyui.treeAll(list, "id,children,text:name".split(","), res);
	}

	/**
	 * 组织机构角色
	 * 
	 * @author WU
	 * @date 2016年4月28日 下午5:20:54
	 * @param req
	 * @return
	 */
	@RequestMapping
	public String departRoleList(HttpServletRequest req) {
		return "sys/department/departRoleList";
	}

	/**
	 * 组织机构角色数据
	 * 
	 * @author WU
	 * @date 2016年5月16日 下午2:32:05
	 * @param role
	 * @param page
	 * @param res
	 * @param req
	 */
	@RequestMapping
	public void departRolelistData(RoleEntity role, Page page, HttpServletResponse res, HttpServletRequest req) {
		QbcQuery qbc = new QbcQuery(role, req.getParameterMap());
		qbc.createAlias("depart");
		qbc.add(Restrictions.eq("depart.departCode", req.getParameter("departCode")));
		service.getPage(qbc, page);
		Easyui.datagrid(page, res);
	}

	/**
	 * 组织机构角色编辑
	 * 
	 * @author WU
	 * @date 2016年5月16日 下午2:35:13
	 * @param req
	 * @return
	 */
	@RequestMapping
	public String departRole(HttpServletRequest req, RoleEntity role) {
		req.setAttribute("zNodes", departService.departRole(role));
		if (role.getId() != null) {
			role = service.get(RoleEntity.class, role.getId());
		}
		req.setAttribute("page", role);
		return "sys/department/departRole";
	}

	/**
	 * 组织机构角色编辑
	 * 
	 * @author WU
	 * @date 2016年5月16日 下午4:21:06
	 * @param role
	 * @return
	 */

	@ResponseBody
	@RequestMapping
	public AjaxJson saveDepartRole(RoleEntity role, String[] perm, String[] funIds) {
		AjaxJson j = new AjaxJson();
		try {
			departService.saveDepartRole(role, perm, funIds);
		} catch (Exception e) {
			j.setException(e);
			e.printStackTrace();
		}
		return j;
	}

	/**
	 * 删除组织机构下的角色
	 * 
	 * @author WU
	 * @date 2016年5月16日 下午4:19:23
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping
	public AjaxJson delDepartRole(String id) {
		AjaxJson j = new AjaxJson();
		try {
			departService.delete(departService.get(RoleEntity.class, id));
		} catch (Exception e) {
			j.setException(e);
			e.printStackTrace();
		}
		return j;
	}

	/**
	 * 数据权限列表
	 * 
	 * @author WU
	 * @date 2016年4月3日 下午11:59:16
	 * @return
	 */
	@RequestMapping
	public String permissionList() {
		return "sys/department/permissionList";
	}

	/**
	 * 职务列表
	 * 
	 * @author WU
	 * @date 2016年6月6日 上午11:44:03
	 * @return
	 */
	@RequestMapping
	public String selectDuty() {
		return "sys/department/selectDuty";
	}

	/**
	 * 职务数据
	 * 
	 * @author WU
	 * @date 2016年6月6日 上午11:44:06
	 * @param code
	 * @param page
	 * @param res
	 * @param req
	 */
	@RequestMapping
	public void dutylistData(CodeEntity code, Page page, HttpServletResponse res, HttpServletRequest req) {
		QbcQuery qbc = new QbcQuery(code, req.getParameterMap());
		service.getPage(qbc, page);
		Easyui.datagrid(page, res);
	}

	/***
	 * 
	 * @author WU
	 * @date 2016年6月8日 下午5:27:44
	 * @return
	 */
	@RequestMapping
	public String departLeaderList() {
		return "sys/department/departLeaderList";
	}

	/**
	 * 
	 * @author WU
	 * @date 2016年6月8日 下午5:28:43
	 * @param leader
	 * @param page
	 * @param res
	 * @param req
	 */
	@RequestMapping
	public void leaderListData(LeaderEntity leader, Page page, HttpServletResponse res, HttpServletRequest req) {
		QbcQuery qbc = new QbcQuery(leader);
		qbc.createAlias("depart");
		qbc.add(Restrictions.eq("depart.departCode", req.getParameter("departCode")));
		service.getPage(qbc, page);
		Easyui.datagrid(page, res);
	}

	/**
	 * 
	 * @author WU
	 * @date 2016年6月13日 上午10:39:07
	 * @return
	 */
	@RequestMapping
	public String departLeader(LeaderEntity leader, HttpServletRequest req) {
		if (leader.getId() != null) {
			leader = service.get(LeaderEntity.class, leader.getId());
		}
		if (leader.getDepart() != null && leader.getDepart().getDepartCode() != null) {
			leader.setDepart(service.get(DepartmentEntity.class, "departCode", leader.getDepart().getDepartCode()));
		}
		req.setAttribute("page", leader);
		return "sys/department/departLeader";
	}

	/**
	 * 
	 * @author WU
	 * @date 2016年6月13日 上午10:38:38
	 * @param leader
	 * @return
	 */
	@ResponseBody
	@RequestMapping
	public AjaxJson saveLeader(LeaderEntity leader) {
		AjaxJson j = new AjaxJson();
		try {
			departService.saveOrUpdate(leader);
		} catch (Exception e) {
			j.setException(e);
			e.printStackTrace();
		}
		return j;
	}

	/**
	 * 
	 * @author WU
	 * @date 2016年6月13日 上午10:38:42
	 * @param leader
	 * @return
	 */
	@ResponseBody
	@RequestMapping
	public AjaxJson delLeader(LeaderEntity leader) {
		AjaxJson j = new AjaxJson();
		try {
			departService.delete(leader);
		} catch (Exception e) {
			j.setException(e);
			e.printStackTrace();
		}
		return j;
	}

	/**
	 * @Title: departUserList
	 * @Description: 部门用户列表
	 * @param req
	 * @return String
	 * @throws @exception
	 * @author fly
	 * @date 2016年12月8日 下午3:10:29
	 */
	@RequestMapping
	public String departUserList(HttpServletRequest req) {
		return "sys/department/departUserList";
	}

	/**
	 * @Title: userListData
	 * @Description: 用户列表数据
	 * @param page
	 * @param res
	 * @param req
	 *            void
	 * @throws @exception
	 * @author fly
	 * @date 2016年12月8日 下午3:10:47
	 */
	@RequestMapping
	public void departUserGird(Page page, HttpServletResponse res, HttpServletRequest req) {
		StringBuffer where = new StringBuffer(this.openPermission("t"));
		departService.departUserGird(where, page, req);
		Easyui.datagrid(page, res);
	}

	/**
	 * 
	 * @author WU
	 * @date 2017年3月31日 下午1:53:29
	 * @param req
	 * @return
	 */
	@RequestMapping
	public String selectDepartUserList(HttpServletRequest req) {
		return "sys/department/selectDepartUserList";
	}

	/**
	 * 
	 * @author WU
	 * @date 2017年3月31日 上午10:41:10
	 * @param req
	 * @return
	 */
	@RequestMapping
	public String departUser(DepartUserEntity du, HttpServletRequest req) {
		if (du.getId() != null) {
			du = service.get(DepartUserEntity.class, du.getId());
			req.setAttribute("page", du.getUser());

			QbcQuery qbc = new QbcQuery(UserRoleEntity.class);
			qbc.add(Restrictions.eq("depart.id", du.getDepart().getId()));
			qbc.add(Restrictions.eq("user.id", du.getUser().getId()));
			List<UserRoleEntity> list = service.getList(qbc);
			req.setAttribute("list", list);
		}

		List<CodeEntity> list = ClientManager.getInstance().getCodeList("userState");
		JSONObject map = new JSONObject();
		for (int i = 0; i < list.size(); i++) {
			map.put(list.get(i).getValue(), list.get(i).getName());
		}
		req.setAttribute("map", map);
		return "sys/department/departUser";
	}

	/**
	 * 
	 * @author WU
	 * @date 2017年3月31日 上午10:57:48
	 * @return
	 */
	@ResponseBody
	@RequestMapping
	public AjaxJson saveDepartUser(String departId, String[] user, String[] role) {
		AjaxJson j = new AjaxJson();
		try {
			departService.saveDepartUser(departId, user, role);
		} catch (Exception e) {
			j.setException(e);
			e.printStackTrace();
		}
		return j;
	}

	/**
	 * 
	 * @author WU
	 * @date 2017年4月1日 下午2:17:32
	 * @param du
	 * @return
	 */
	@ResponseBody
	@RequestMapping
	public AjaxJson delDepartUser(DepartUserEntity du) {
		AjaxJson j = new AjaxJson();
		try {
			departService.delDepartUser(du);
		} catch (Exception e) {
			j.setException(e);
			e.printStackTrace();
		}
		return j;
	}

	/**
	 * 数据更新(角色上添加部门ID)
	 * 
	 * @author WU
	 * @date 2017年4月1日 下午2:57:01
	 * @return
	 */
	@ResponseBody
	@RequestMapping
	public AjaxJson updateRole() {
		AjaxJson j = new AjaxJson();
		try {
			departService.updateRole();
		} catch (Exception e) {
			j.setException(e);
			e.printStackTrace();
		}
		return j;
	}
	
	private void departPermission(QbcQuery qbc) {
		String url = HttpUtil.getRequest().getServletPath().substring(1);
		Client client = ClientManager.getInstance().getClientSession();
		String departCode = client.getDepart().getDepartCode();
		List<PermissionEntity> list = client.getPreList();
		Map<String, String> map = new HashMap<String, String>();

		if (list != null && list.size() > 0 && !client.getUser().isAdmin()) {
			for (int i = 0; i < list.size(); i++) {
				map.put(client.getUser().getId(), "userCode");
				departCode = MessageFormat.format(list.get(i).getDepartCode(), departCode);
				if (StringUtil.isNotEmpty(list.get(i).getUrl())) {
					if (list.get(i).getUrl().contains(url)) {
						map.put("%" + departCode + "%", "depCode");
					} else {
						continue;
					}
				} else {
					map.put("%" + departCode + "%", "depCode");
				}

			}
		}

		List<Criterion> clist = new ArrayList<Criterion>();
		for (String depCode : map.keySet()) {
			String value = map.get(depCode);
			if ("userCode".equals(value)) {
				clist.add(Restrictions.eq(value, depCode));
			} else {
				clist.add(Restrictions.like(value, depCode));
			}
		}
		if (map.size() > 0) {
			Criterion[] crits = new Criterion[map.size()];
			qbc.add(Restrictions.or(clist.toArray(crits)));
			qbc.add(Restrictions.like("depCode", "%"+client.getCompany().getDepartCode() + "%"));

		}
	}
}
